package com.leancloud.login.user;

import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.reflect.TypeToken;
import com.vise.xsnow.common.GsonUtil;
import com.vise.xsnow.event.BusManager;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.http.callback.UCallback;
import com.vise.xsnow.http.request.PostRequest;

import java.io.File;
import java.util.Map;

import cn.bmob.v3.http.bean.Api;
import tech.com.commoncore.ApplyName;
import tech.com.commoncore.base.BaseApplication;
import tech.com.commoncore.constant.ApiConstant;
import tech.com.commoncore.event.LoginChangeEvent;

import tech.com.commoncore.user.CurrentUser;
import tech.com.commoncore.user.NUser;
import tech.com.commoncore.utils.SPHelper;

public class UserServerImp implements UserServer {
    private static UserServerImp serverImp;

    private static final String USER_INFO_KEY = "userInfoKey";
    private static CurrentUser currentUser;
    private Context mContext;

    public static UserServerImp getInstance() {
        synchronized (UserServerImp.class) {
            if (serverImp == null)
                serverImp = new UserServerImp();
        }
        return serverImp;
    }

    private UserServerImp() {
        mContext = BaseApplication.getInstance();
    }

    @Override
    public void requestRegisteredVerificationCode(String number, String signName, final LoginBack back) {
        ViseHttp.GET("/api/user/verification_code/send/")
                .baseUrl(ApiConstant.BASE_URL)
                .addParam("username", number)
                .addParam("signname", signName)
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        JSONObject jsonObject = JSONObject.parseObject(data);
                        if (jsonObject.getIntValue("code") == 1) {
                            handlerNewsBack(back, null, null);
                        } else {
                            handlerNewsBack(back, null, jsonObject.getString("msg"));
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        handlerNewsBack(back, null, errMsg);
                    }
                });
    }






//    api/user/verification_code/send?username=15360608585&signname=99999
    @Override
    public void requestAllVerificationCode(String phone, String app_name,String apply_name ,final LoginBack back) {
        ViseHttp.POST("/new_api/NewSms/newSend")
                .baseUrl(ApiConstant.BASE_URL)
                 .addForm("phone", phone)
                .addForm("app_name", app_name)
                .addForm("apply_name", apply_name)
//                .addParam("username", number)
//                .addParam("signname", signName)
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        JSONObject jsonObject = JSONObject.parseObject(data);
                        if (jsonObject.getIntValue("code") == 1) {
                            handlerNewsBack(back, null, null);
                        } else {
                            handlerNewsBack(back, null, jsonObject.getString("msg"));
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        handlerNewsBack(back, null, errMsg);
                    }
                });

    }




    @Override
    public void userRegistered(String phone, String password, String code, String app,String apply_name,String is_validate,final LoginBack back) {
        ViseHttp.POST("user/communal/register")
                .baseUrl(ApiConstant.BASE_URL)
//        ViseHttp.POST("/api/user/public/third_register_and_login/")
                .addForm("username", phone)
                .addForm("password", password)
                .addForm("verification_code", code)
                .addForm("app", app)
                .addForm("apply_name", apply_name)
                .addForm("is_validate", is_validate)
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        JSONObject jsonObject = JSONObject.parseObject(data);
                        if (jsonObject.getIntValue("code") == 1) {
                            handlerNewsBack(back, null, null);
                        } else {
                            handlerNewsBack(back, null, jsonObject.getString("msg"));
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        handlerNewsBack(back, null, errMsg);
                    }
                });
    }


    @Override
    public void userLogin(String username, String password, String app, final LoginBack back) {
        ViseHttp.POST("/api/user/public/login/")
                .baseUrl(ApiConstant.BASE_URL)
//          ViseHttp.POST("/user/communal/login")
                .addForm("username", username)
                .addForm("password", password)
                .addForm("device_type", "android")
                .addForm("app", app)
                .addForm("apply_name", ApplyName.ApplyName)

                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        try {
                            JSONObject jsonObject = JSONObject.parseObject(data);
                            if (jsonObject.getIntValue("code") == 1) {
                                //   plog.paly("登录后的用户数据是");
                                NUser nUser = GsonUtil.gson().fromJson(jsonObject.getString("data"), new TypeToken<NUser>() {}.getType());
//                                NUser nUser = JSONObject.parseObject(jsonObject.getString("data"), NUser.class);
                                if (nUser != null) {
                                    currentUser = new CurrentUser(nUser);
                                    currentUser.setLogin(true);
                                    SPHelper.saveDeviceData(mContext, USER_INFO_KEY, currentUser);
                                    Map<String, String> headMap = ViseHttp.CONFIG().getGlobalHeaders();
                                    headMap.put("XX-Token", currentUser.getToken());
                                    headMap.put("XX-Device-Type", "android");
                                    ViseHttp.CONFIG().globalHeaders(headMap);
                                }
                                handlerNewsBack(back, null, null);
                            } else {
                                handlerNewsBack(back, null, jsonObject.getString("msg"));
                            }
                        } catch (JSONException e) {
                            handlerNewsBack(back, null, "解析错误");
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        handlerNewsBack(back, null, errMsg);
                    }
                });
    }

    @Override
    public void allianceLogin(String objectId, final String username, final LoginBack back) {
        ViseHttp.POST("/api/user/public/third_register_and_login/")
                .baseUrl(ApiConstant.BASE_URL)
                .addForm("username", username)
                .addForm("object_id", objectId)
                .addForm("app_type", "android")
                .addForm("apply_name", "qkltg0704")
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        JSONObject jsonObject = JSONObject.parseObject(data);
                        Log.e("PWDebug", "登录返回的信息是:" + jsonObject.toString());
                        if (jsonObject.getIntValue("code") == 1) {
                            NUser userTool = JSONObject.parseObject(jsonObject.getString("data"), NUser.class);
                            if (userTool != null) {
                                currentUser = new CurrentUser(userTool);
                                currentUser.setLogin(true);
                                if (currentUser.getNickName() == null || currentUser.getNickName().isEmpty()) {
                                    modifyUserNickName(currentUser.getToken(), username, null);
                                }
                                SPHelper.saveDeviceData(mContext, USER_INFO_KEY, currentUser);

                                Map<String, String> head = ViseHttp.CONFIG().getGlobalHeaders();
                                head.put("XX-Token", currentUser.getToken());
                                head.put("XX-Device-Type", "android");
                                ViseHttp.CONFIG().globalHeaders(head);
                            }
                            handlerNewsBack(back, null, null);
                        } else {
                            handlerNewsBack(back, null, jsonObject.getString("msg"));
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        handlerNewsBack(back, null, errMsg);
                        Log.e("PWDebug", "错误信息是:" + errMsg);
                    }
                });

    }

    @Override
    public void logout(final LoginBack back) {
        ViseHttp.POST("/api/user/public/logout/")
                .baseUrl(ApiConstant.BASE_URL)
                .addHeader("XX-Token", getCurrentUser().getToken())
                .addHeader("XX-Device-Type", "android")
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                    }
                });

        ViseHttp.CONFIG().globalHeaders(null);
        currentUser = null;
        SPHelper.removeSF(mContext, USER_INFO_KEY);
        handlerNewsBack(back, null, null);
    }

    @Override
    public boolean isLogin() {
        if (getCurrentUser() == null) {
            return false;
        }
        if (!getCurrentUser().isLogin) {
            return false;
        }
        return true;
    }

    @Override
    public CurrentUser getCurrentUser() {
        if (currentUser != null) {
            return currentUser;
        }
        CurrentUser user = SPHelper.getDeviceData(mContext, USER_INFO_KEY);
        if (user == null) {
            return null;
        }
        return user;
    }

    @Override
    public void weModifyPassword(String token, String oldPassword, String password, String confirmPassword, final LoginBack back) {
        ViseHttp.POST("/api/user/profile/changePassword/")
                .baseUrl(ApiConstant.BASE_URL)
                .addHeader("XX-Token", token)
                .addHeader("XX-Device-Type", "android")
                .addForm("old_password", oldPassword)
                .addForm("password", password)
                .addForm("confirm_password", confirmPassword)
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        JSONObject jsonObject = JSONObject.parseObject(data);
                        if (jsonObject.getIntValue("code") == 1) {
                            handlerNewsBack(back, null, null);
                        } else {
                            handlerNewsBack(back, null, jsonObject.getString("msg"));
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        handlerNewsBack(back, null, errMsg);
                    }
                });
    }

    @Override
    public void weRetrievePassword(String certificate, String password, String verificationCode, String apply_name, final LoginBack back) {
        ViseHttp.POST("/api/user/public/passwordReset/")
//        ViseHttp.POST("/user/communal/passwordReset")
                .baseUrl(ApiConstant.BASE_URL)
                .addForm("username", certificate)
                .addForm("password", password)
                .addForm("verification_code", verificationCode)
                .addForm("app", "")
                .addForm("apply_name", apply_name)
                .addForm("compatible", 2+"")
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        JSONObject jsonObject = JSONObject.parseObject(data);
                        if (jsonObject.getIntValue("code") == 1) {
                            handlerNewsBack(back, null, null);
                        } else {
                            handlerNewsBack(back, null, jsonObject.getString("msg"));
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        handlerNewsBack(back, null, errMsg);
                    }
                });
    }

    @Override
    public void weBindingEmail(String token, String email, String verificationCode, final LoginBack back) {
        ViseHttp.POST("/api/user/profile/bindingEmail/")
                .baseUrl(ApiConstant.BASE_URL)
                .addHeader("XX-Token", token)
                .addHeader("XX-Device-Type", "android")
                .addForm("email", email)
                .addForm("verification_code", verificationCode)
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        JSONObject jsonObject = JSONObject.parseObject(data);
                        if (jsonObject.getIntValue("code") == 1) {
                            handlerNewsBack(back, null, null);
                        } else {
                            handlerNewsBack(back, null, jsonObject.getString("msg"));
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        handlerNewsBack(back, null, errMsg);
                    }
                });
    }

    @Override
    public void weBindingMobile(String token, String mobile, String verificationCode, String app, final LoginBack back) {
        ViseHttp.POST("/api/user/profile/bindingEmail/")
                .baseUrl(ApiConstant.BASE_URL)
                .addHeader("XX-Token", token)
                .addHeader("XX-Device-Type", "android")
                .addHeader("mobile", mobile)
                .addHeader("verification_code", verificationCode)
                .addHeader("app", app)
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        JSONObject jsonObject = JSONObject.parseObject(data);
                        if (jsonObject.getIntValue("code") == 1) {
                            handlerNewsBack(back, null, null);
                        } else {
                            handlerNewsBack(back, null, jsonObject.getString("msg"));
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        handlerNewsBack(back, null, errMsg);
                    }
                });
    }

    @Override
    public void modifyUserNickName(String token, String nikeName, LoginBack back) {
        modifyUserInfo(token, nikeName, null, null, null, -1, -1, back);
    }

    @Override
    public void modifyUserAvatar(String token, String avatar, LoginBack back) {
        modifyUserInfo(token, null, avatar, null, null, -1, -1, back);
    }

    @Override
    public void modifyUserSignature(String token, String signature, LoginBack back) {
        modifyUserInfo(token, null, null, signature, null, -1, -1, back);
    }

    @Override
    public void modifyUserUrl(String token, String userUrl, LoginBack back) {
        modifyUserInfo(token, null, null, null, userUrl, -1, -1, back);
    }

    @Override
    public void modifyUserSex(String token, int sex, LoginBack back) {
        modifyUserInfo(token, null, null, null, null, sex, -1, back);
    }

    @Override
    public void modifyUserBirthday(String token, int birthday, LoginBack back) {
        modifyUserInfo(token, null, null, null, null, -1, birthday, back);
    }

    @Override
    public void modifyUserInfo(String token, String nickName, String avatar, String signature, String userUrl, int sex, int birthday, final LoginBack back) {
        PostRequest postRequest = ViseHttp.POST("/api/user/profile/userInfo/")
                .addHeader("XX-Token", token)
                .addHeader("XX-Device-Type", "android");
        if (nickName != null)
            postRequest.addForm("user_nickname", nickName);
        if (avatar != null)
            postRequest.addForm("avatar", avatar);
        if (signature != null)
            postRequest.addForm("signature", signature);
        if (userUrl != null)
            postRequest.addForm("user_url", userUrl);
        if (sex > -1)
            postRequest.addForm("sex", String.valueOf(sex));
        if (birthday != -1)
            postRequest.addForm("birthday", birthday);
        postRequest.request(new ACallback<String>() {
            @Override
            public void onSuccess(String data) {
                JSONObject jsonObject = JSONObject.parseObject(data);
                if (jsonObject.getIntValue("code") == 1) {
                    handlerNewsBack(back, null, null);
                    updateUserInfo(getCurrentUser().getToken(), null);
                } else {
                    handlerNewsBack(back, null, jsonObject.getString("msg"));
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                handlerNewsBack(back, null, errMsg);
            }
        });

    }

    @Override
    public void updateUserInfo(String token, final LoginBack back) {
        ViseHttp.GET("/api/user/profile/userInfo/")
                .baseUrl(ApiConstant.BASE_URL)
                .addHeader("XX-Token", token)
                .addHeader("XX-Device-Type", "android")
                .tag("/api/user/profile/userInfo/")
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        JSONObject jsonObject = JSONObject.parseObject(data);
                        if (jsonObject.getIntValue("code") == 1) {
                            BaseUserInfo baseUserInfo = JSONObject.parseObject(jsonObject.getString("data"), BaseUserInfo.class);
                            CurrentUser user = getCurrentUser();
                            if (user != null && baseUserInfo != null) {
                                user.setUserType(baseUserInfo.user_type);
                                user.setUserLogin(baseUserInfo.user_login);
                                user.setMobile(baseUserInfo.mobile);
                                user.setEmail(baseUserInfo.user_email);
                                user.setNickName(baseUserInfo.user_nickname);
                                user.setAvatar(baseUserInfo.avatar);
                                user.setSignature(baseUserInfo.signature);
                                user.setUserUrl(baseUserInfo.user_url);
                                user.setSex(baseUserInfo.sex);
                                user.setBirthday(baseUserInfo.birthday);
                                user.setScore(baseUserInfo.score);
                                user.setCoin(baseUserInfo.coin);
                                user.setUserStatus(baseUserInfo.user_status);
                                user.setUserActivationKey(baseUserInfo.user_activation_key);
                                user.setCreateTime(baseUserInfo.create_time);
                                user.setLastLoginTime(baseUserInfo.last_login_time);
                                user.setLastLoginIp(baseUserInfo.last_login_ip);
                                SPHelper.saveDeviceData(mContext, USER_INFO_KEY, user);
                                //LoginChangeEvent
                                BusManager.getBus().post(new LoginChangeEvent(true));
                            }
                            handlerNewsBack(back, null, null);
                        } else {
                            handlerNewsBack(back, null, jsonObject.getString("msg"));
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {

                    }
                });
    }

    @Override
    public void uploadImage(String token, String file, final LoginBack back) {
        ViseHttp.UPLOAD("/api/user/upload/one/")
                .baseUrl(ApiConstant.BASE_URL)
                .addHeader("XX-Token", token)
                .addHeader("XX-Device-Type", "android")
                .addFile("file", new File(file), new UCallback() {
                    @Override
                    public void onProgress(long currentLength, long totalLength, float percent) {

                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {

                    }
                }).request(new ACallback<String>() {
            @Override
            public void onSuccess(String data) {
                JSONObject jsonObject = JSONObject.parseObject(data);
                if (jsonObject.getIntValue("code") == 1) {
                    NImageInfo imageInfo = JSONObject.parseObject(jsonObject.getString("data"), NImageInfo.class);
                    handlerNewsBack(back, imageInfo, null);
                } else {
                    handlerNewsBack(back, null, jsonObject.getString("msg"));
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                handlerNewsBack(back, null, "网络异常");
            }
        });
    }

    @Override
    public void emialReg(String emal, String pwd, String apply_name, final LoginBack back) {
        ViseHttp.POST("api/user/public/register")
                .baseUrl(ApiConstant.BASE_URL)
                .addForm("username", emal)
                .addForm("apply_name", apply_name)
                .addForm("password", pwd).tag(" api/user/public/register").request(new ACallback<String>() {
            @Override
            public void onSuccess(String data) {
                JSONObject jsonObject = JSONObject.parseObject(data);
                if (jsonObject.getIntValue("code") == 1) {
                    handlerNewsBack(back, null, null);
                } else {
                    handlerNewsBack(back, null, jsonObject.getString("msg"));
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                handlerNewsBack(back, null, "网络异常");
            }
        });

    }

    private synchronized void handlerNewsBack(LoginBack back, Object o, String err) {
        if (back != null) {
            back.onBack(o, err);
        }
    }
}
